//
//  FQDArticleCommentCellItemProvider.m
//  FakeQDaily
//
//  Created by mewxiv on 8/31/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDArticleCommentCellItemProvider.h"
#import "FQDRestModel.h"
#import "QDailyAPI.h"

#import "YYModel.h"

static NSString *const kArticleCommentFeed = @"article_comments";

@interface FQDArticleCommentCellItemProvider ()
@property (nonatomic, strong) NSArray *comments;
@end

@implementation FQDArticleCommentCellItemProvider

- (void)getCellItems:(NSString *)cursorKey completion:(QDailyAPICompleteBlock)completion
{
    [[QDailyAPI sharedAPI] getArticleComments:self.feedId key:cursorKey completion:completion];
}

- (void)parseResponse:(id)response isLatest:(BOOL)isLatest
{
    self.comments = [NSArray yy_modelArrayWithClass:[FQDComment class]
                                               json:response[@"comments"]];
}

- (void)populateNewCellItemsTo:(NSMutableArray *)originalCellItems
{
    // 把子评论从父评论的列表中提取出来，并与父评论同级显示
    for (FQDComment *comment in self.comments) {
        [originalCellItems addObject:comment];
        
        if ([comment.child_comments count] > 0) {
            for (FQDChildComment *childComment in comment.child_comments) {
                [originalCellItems addObject:childComment];
            }
        }
    }
}

- (void)addNewComment:(FQDComment *)comment
{
    [self modifyCellItemsWithBlock:^(NSMutableArray *originalCellItems) {
        if ([comment isKindOfClass:[FQDChildComment class]]) {
            FQDChildComment *childComment = (FQDChildComment *)comment;
            NSInteger allCount = [originalCellItems count];
            NSInteger insertIndex = 0;
            for (NSInteger index = 0; index < allCount; index++) {
                FQDComment *iterComment = originalCellItems[index];
                if ([iterComment.ID isEqualToString:childComment.root_id]) {
                    NSMutableArray *muChildComments = [iterComment.child_comments mutableCopy];
                    [muChildComments addObject:childComment];
                    iterComment.child_comments = [muChildComments copy];
                    insertIndex = index + [iterComment.child_comments count];
                    break;
                }
            }
            [originalCellItems insertObject:childComment atIndex:insertIndex];
            
        } else {
            [originalCellItems insertObject:comment atIndex:0];
        }
    }];
}

- (NSString *)cacheId
{
    return kArticleCommentFeed;
}

@end